package com.common.android.utils.http;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONException;
import org.json.JSONObject;

import com.product.android.business.ApplicationVariable;

public class HttpComHandlerJsonCode extends HttpComExt {
	/**
	 * 
	 * Creates a new instance of HttpComExt.
	 * 
	 * @param bNewPro
	 */
	public HttpComHandlerJsonCode(boolean bNewPro) {
		super(bNewPro);
		if (ApplicationVariable.INSTANCE.getCurrentUserInfo() != null) {
			httpclient.setSid(ApplicationVariable.INSTANCE.getCurrentUserInfo()
					.getSessionId() + "");
		}
	}

	public JSONObject postRetJson(String url, JSONObject json) throws HttpException {
		Response response = null;
		HttpException exception = null;
		try {
			response = httpclient.httpRequest(url, json, HttpPost.METHOD_NAME,
					null, null, null);
		} catch (HttpException e) {
			exception = e;
		}
		JSONObject jsonResult = null;
		// 不知道是否需要重登，所以解析后判断
		if (response != null && exception == null) {
			String str = response.asString();
			try {
				jsonResult = new JSONObject(str);
				if (jsonResult.optInt("code") == HttpBaseClient.NOT_AUTHORIZED) {
					exception = new HttpException(str,
							HttpBaseClient.NOT_AUTHORIZED);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		if (exception != null) {
			url = getSidAndReplceUrl(url, exception);
			response = httpclient.httpRequest(url, json, HttpPost.METHOD_NAME,
					null, null, null);
			jsonResult = response.asJSONObject();
		}
		return jsonResult;
	}

	public JSONObject getRetJson(String url) throws HttpException {
		Response response = null;
		HttpException exception = null;
		try {
			response = httpclient.httpRequest(url, null, HttpGet.METHOD_NAME,
					null, null, null);
		} catch (HttpException e) {
			exception = e;
		}
		JSONObject jsonResult = null;
		// 不知道是否需要重登，所以解析后判断
		if (response != null && exception == null) {
			String str = response.asString();
			try {
				jsonResult = new JSONObject(str);
				if (jsonResult.optInt("code") == HttpBaseClient.NOT_AUTHORIZED) {
					exception = new HttpException(str,
							HttpBaseClient.NOT_AUTHORIZED);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		if (exception != null) {
			url = getSidAndReplceUrl(url, exception);
			response = httpclient.httpRequest(url, null, HttpGet.METHOD_NAME,
					null, null, null);
			jsonResult = response.asJSONObject();
		}
		return jsonResult;
	}
}
